package com.huiminpay.merchant.controller;

import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.common.SecurityUtil;
import com.huiminpay.merchant.dto.dto.AppDTO;
import com.huiminpay.common.cache.execption.BizException;
import com.huiminpay.merchant.service.IAppService;
import com.huiminpay.merchant.vo.AppVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@Api(value = "应用操作相关",tags = "应用操作相关",description = "应用操作相关1")
public class AppController {
    @Reference
    IAppService iAppService;


    @ApiOperation(value = "创建应用")
    @PostMapping("/my/apps")
  public AppDTO createApp(@RequestBody AppVo appVo){
        //非空校验
         if (StringUtils.isEmpty(appVo.getAppName())){
             throw new BizException(CommonErrorCode.E_200237);
         }
        //保存数据库
        AppDTO appDTO = new AppDTO();
        Long merchantId = SecurityUtil.getMerchantId();
        appDTO.setMerchantId(merchantId);
        appDTO.setAppName(appVo.getAppName());
        appDTO.setPublicKey(appVo.getPublicKey());
//        1402253684330139600
//        1402253684330139650

        return iAppService.createApp(appDTO);
    }

    @ApiOperation(value = "查询我的应用")
    @GetMapping("/my/apps")
    public List<AppDTO> selectMyApps(){

        Long merchantId = SecurityUtil.getMerchantId();
        List<AppDTO> appDTOS = iAppService.myApps(merchantId);
        return appDTOS;
    }


    @ApiOperation(value = "修改应用")
    @PutMapping("/my/apps")
    public AppDTO updateApp(@RequestBody AppVo appVo){
        //非空校验
        if (StringUtils.isEmpty(appVo.getAppName())){
            throw new BizException(CommonErrorCode.E_200237);
        }
        if (StringUtils.isEmpty(appVo.getAppId())){
            throw new BizException(CommonErrorCode.E_200239);
        }
        AppDTO appDTO = new AppDTO();
        appDTO.setMerchantId(null);
        BeanUtils.copyProperties(appVo,appDTO);
        //更新数据库
        return iAppService.updateApp(appDTO);
    }
}
